//
//  StreamFirstLevelViewController.m
//  CarpoolWithFriends
//
//  Created by Kai Wang on 5/6/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "StreamFirstLevelViewController.h"
#import "FeedViewController.h"
#import "NotificationViewController.h"
#import "PostStepOneViewController.h"
#import "MapViewController.h"
#import "CarpoolWithFriendsAdapter.h"

@interface StreamFirstLevelViewController()

// Private Properties:
//@property (retain, nonatomic) UIPanGestureRecognizer *navigationBarPanGestureRecognizer;

// Private Methods:
-(void)revealNotification:(id)sender;
-(void)revealNewPost:(id)sender;
-(void)revealMap:(id)sender;

@end

@implementation StreamFirstLevelViewController
@synthesize streamTableView;
@synthesize tableViewCell;
@synthesize segment;

//@synthesize navigationBarPanGestureRecognizer;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    //    [self.navigationController.navigationBar removeGestureRecognizer:self.navigationBarPanGestureRecognizer];
    //	[navigationBarPanGestureRecognizer release], self.navigationBarPanGestureRecognizer = nil;
    
    [tableViewCell release];
    [streamTableView release];
    [popularStream release];
    [segment release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
 * The following lines are crucial to understanding how the ZUUIRevealController works.
 *
 * In this example, the FrontViewController is contained inside of a UINavigationController.
 * And the UINavigationController is contained inside of a ZUUIRevealController. Thus the
 * following hierarchy is created:
 *
 * - ZUUIRevealController is parent of:
 * - - UINavigationController is parent of:
 * - - - FrontViewController
 *
 * If you don't want the UINavigationController in between (which is totally fine) all you need to
 * do is to adjust the if-condition below in a way to suit your needs. If the hierarchy were to look 
 * like this:
 *
 * - ZUUIRevealController is parent of:
 * - - FrontViewController
 * 
 * Without a UINavigationController in between, you'd need to change:
 * self.navigationController.parentViewController TO: self.parentViewController
 *
 * Note that self.navigationController is equal to self.parentViewController. Thus you could generalize
 * the code even more by calling self.parentViewController.parentViewController. In order to make 
 * the code easier to understand I decided to go with self.navigationController.
 *
 */
- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];

    //change navigation bar color
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.0f/255.0f green:176.0f/255.0f blue:217.0f/255.0f alpha:1.0f];
    
    //	if ([self.navigationController.parentViewController respondsToSelector:@selector(revealGesture:)] && [self.navigationController.parentViewController respondsToSelector:@selector(revealToggle:)])
    //	{
    //		// Check if a UIPanGestureRecognizer already sits atop our NavigationBar.
    //		if (![[self.navigationController.navigationBar gestureRecognizers] containsObject:self.navigationBarPanGestureRecognizer])
    //		{
    //			// If not, allocate one and add it.
    //			UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self.navigationController.parentViewController action:@selector(revealGesture:)];
    //			self.navigationBarPanGestureRecognizer = panGestureRecognizer;
    //			[panGestureRecognizer release];
    //			
    //			[self.navigationController.navigationBar addGestureRecognizer:self.navigationBarPanGestureRecognizer];
    //		}
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // load popular stream data when view is loaded
    NSMutableDictionary *retDict;
    [CarpoolWithFriendsAdapter requestPopularStreamWithUserId:@"abc" retData:&retDict];
    popularStream = [[NSArray alloc]initWithArray:[retDict objectForKey:@"stream"] copyItems:YES];    
    stream = popularStream;
    
    self.title = NSLocalizedString(@"Stream", @"Stream");
    
    // Check if we have a revealButton already.
    if (![self.navigationItem leftBarButtonItem])
    {
        // If not, allocate one and add it.
        UIBarButtonItem *revealButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu_button.png"] style:UIBarButtonItemStylePlain target:self.navigationController.parentViewController action:@selector(revealToggle:)];
        
        self.navigationItem.leftBarButtonItem = revealButton;
        [revealButton release];
    }
    
    // right navigation button
    // Including Map Button, Compose Button, inbox button
    if(![self.navigationItem rightBarButtonItem])
    {
        // Create a toolbar to have two buttons on the right side
        UIToolbar *tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 80, 44.01)];
        tools.tintColor = [UIColor colorWithRed:0.0f/255.0f green:176.0f/255.0f blue:217.0f/255.0f alpha:1.0f];
        
        // Create the array to hold the buttons, which then gets added to the toolbar
        NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity: 3];
        
        UIBarButtonItem *aBarButtonItem;
        UIImage *aButtonImage;
        UIButton *aButton;
        
        // create a standard "Map" button
        aButtonImage = [UIImage imageNamed:@"map.png"];
        aButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [aButton setImage:aButtonImage forState:UIControlStateNormal];
        aButton.frame = CGRectMake(0.0, 0.0, aButtonImage.size.width, aButtonImage.size.height);
        aBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:aButton];
        [aButton addTarget:self action:@selector(revealMap:) forControlEvents:UIControlEventTouchUpInside];
        
        [buttons addObject:aBarButtonItem];
        
        [aButtonImage release];
        [aButton release];
        [aBarButtonItem release];
        
        // Create a spacer
        aBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        [buttons addObject:aBarButtonItem];
        [aBarButtonItem release];
        
        // Create a standard "Compose" button
        aBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(revealNewPost:)];
        //        aBarButtonItem.style = UIBarButtonItemStyleBordered;
        [buttons addObject:aBarButtonItem];
        [aBarButtonItem release];
        
        // stick the buttons in the toolbar
        [tools setItems:buttons animated:NO];
        
        [buttons release];
        
        // put the toolbar in the nav bar
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];
        
        [tools release];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (IBAction)segmentChanged:(id)sender
{
    NSInteger index = [segment selectedSegmentIndex];
    debug_int(index);
    switch (index) {
        case 0:
        {
            // the popular stream is already loaded when the view is first time loaded
            // popular stream
            stream = popularStream;
            break;
        }
        case 1:
        {
            if(friendsStream == nil)
            {
                NSMutableDictionary *retDict;
                [CarpoolWithFriendsAdapter requestAllFriendsStreamWithUserId:@"abc" retData:&retDict];
                friendsStream = [[NSArray alloc]initWithArray:[retDict objectForKey:@"stream"] copyItems:YES];              
            }
            stream = friendsStream;
            break;
        }
        case 2:
        {
            if(myStream == nil)
            {
                NSMutableDictionary *retDict;
                [CarpoolWithFriendsAdapter requestStreamWithUserId:@"abc" retData:&retDict];
                myStream = [[NSArray alloc]initWithArray:[retDict objectForKey:@"stream"] copyItems:YES];              
            }
            stream = myStream;
            break;
        }
        default:
            break;
    }
    
    [streamTableView reloadData];
}


#pragma marl - UITableView Data Source
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [stream count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 180.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	
	if (nil == cell)
	{
		[[NSBundle mainBundle] loadNibNamed:@"StreamTableViewCell" owner:self options:nil];
        cell = tableViewCell;
        self.tableViewCell = nil;
        
        if(stream!= nil)
        {
            NSDictionary *feed = [stream objectAtIndex:indexPath.row];
            
            UILabel *label;
            label = (UILabel*)[cell viewWithTag:1];
            label.text = [feed objectForKey:@"owner_name"];
            
            label = (UILabel*)[cell viewWithTag:2];
            label.text = (NSString*)[feed objectForKey:@"from_place"];
            
            label = (UILabel*)[cell viewWithTag:3];
            label.text = (NSString*)[feed objectForKey:@"to_place"];
            
            label = (UILabel*)[cell viewWithTag:4];
            label.text = [feed objectForKey:@"start_time"];
            
            label = (UILabel*)[cell viewWithTag:5];
            label.text = [feed objectForKey:@"end_time"];
            
            label = (UILabel*)[cell viewWithTag:6];
            label.text = [feed objectForKey:@"seat_num"];
        }
    }
    
	return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FeedViewController *viewController = [[FeedViewController alloc] init];
    [self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
}

-(void)revealNotification:(id)sender
{
    NotificationViewController *viewController = [[NotificationViewController alloc] init];
    //    viewController.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
}

-(void)revealNewPost:(id)sender
{
    PostStepOneViewController *viewController = [[PostStepOneViewController alloc] init];
    [self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
}

-(void)revealMap:(id)sender
{
    MapViewController *viewController = [[MapViewController alloc] init];
    [self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
}

@end
